<?php

namespace app\beautiful\controller\admin\partner;

use app\BaseController;

use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\model\CouponModel;
use app\beautiful\model\GiftbagModel;
use app\beautiful\model\PartnerGiftbagModel;
use app\beautiful\model\setting\PartnerBonusSettingModel;
use app\beautiful\model\setting\PartnerDividendSettingModel;
use app\common\logic\DataLogic;

use app\beautiful\logic\PartnerLogic;

use app\beautiful\model\member\MemberBalanceModel;

use app\beautiful\model\member\MemberIntegralModel;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\partner\PartnerCommissionModel;

use app\beautiful\model\partner\PartnerSettingModel;

use app\beautiful\model\partner\PartnerWithdrawModel;

use app\beautiful\model\PartnerModel;
use app\common\model\ShopDetailModel;
use app\stores\model\partner\PartnerBonusShareLogModel;
use think\facade\Db;
use think\Model;


class PartnerManage extends BaseController{

    protected $name='合伙人';
    /*合伙人列表*/
    public function index()

    {

        $role_id=$this->request->param('role_id/d',1);

        $search=$this->request->param('search');

        $status=$this->request->param('status/d',1);//1正常-1退股

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['role_id','=',$role_id],

            ['status','=',$status],

            ['type','>',0]

        ];

        if(!empty($search)) $where[]=['name|mobile','like','%'.$search.'%'];

        $partner_model= new PartnerModel();

        $partner_model = $partner_model::with(['member']);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['is_expire','add_time_format'];

        $return = DataLogic::getDataList($partner_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $return['list'];

        $dividend_setting = PartnerDividendSettingModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'role_id'=>$role_id])->json(['range'],true)->find();

        foreach ($list as $k=>$v){
            $list[$k]['member_num'] = $v['member']['member_num'];
            $list[$k]['dividend_ratio'] = sprintf("%.2f",0);
            if(in_array($v['type'],[1,2])){
                $price = $v['type']==1?$v['invest_amount']:$v['stored_value_amount'];
                if($dividend_setting){
                    if($range = $dividend_setting->range){
                        for ($i=0;$i<count($range);$i++){
                            if($range[$i]['start']<$price && $price<$range[$i]['end']){
                                $list[$k]['dividend_ratio'] = $range[$i]['ratio'];
                            }
                        }
                    }
                }
            }
            unset($list[$k]['member']);

        }
        $return['list'] = $list;
        //员工合伙人类型
        $return['staff_type'] = $dividend_setting->staff_type;

        //开启分成并且设置了对应类型合伙人的数据，才能添加对应合伙人
        $shop_detail = ShopDetailModel::where('shop_id',$this->request->shopId)->find();
        $return['is_add_partner'] = ($shop_detail->is_open_partner_dividend==1 && !empty($dividend_setting) && !empty($dividend_setting['range']))?1:0;
        return $this->success($return);

    }
    /*显示合伙人*/
    public function show()

    {
        $partner_id = $this->request->param('partner_id/d',0);//1投资2储值3业绩


        if(null === $partner = PartnerModel::with(['member'])->find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');


        $detail=[
            'partner_id'=>$partner->partner_id,

            'role_id'=>$partner->role_id,

            'member_id'=>$partner->member_id,

            'name'=>$partner->name,

            'mobile'=>$partner->mobile,

            'expire_time'=>$partner->expire_time,

            'invest_amount'=>$partner->invest_amount,

            'stored_value_amount'=>$partner->stored_value_amount,

            'give_amount'=>$partner->give_amount,

            'bonus_share'=>$partner->bonus_share,

            'type'=>$partner->type,

            'member_num'=>$partner->member->member_num,

            'nick_name'=>$partner->member->nick_name,

        ];

        $return['detail']=$detail;



        return $this->success($return);



    }
    /*添加/修改合伙人*/
    public function save()

    {
        $partner_id = $this->request->param('partner_id/d',0);
        $type = $this->request->param('type/d',0);//1投资2储值3业绩
        $role_id = $this->request->param('role_id/d');
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        //$expire_time = $this->request->param('expire_time');
        $member_id = $this->request->param('member_id/d',0);
        $invest_amount = $this->request->param('invest_amount/f',0);
        $stored_value_amount = $this->request->param('stored_value_amount/f',0);
        $give_amount = $this->request->param('give_amount/f',0);

        //判断传来的参数
        if(!in_array($role_id,[2,5,6])) return $this->error('参数错误');
        if(empty($name)) return $this->error('请输入股东姓名');
        if(empty($mobile) || !is_mobile($mobile)) return $this->error('请输入股东手机号');
        //if(empty($expire_time)) return $this->error('请选择过期时间');
        //if(false === $expire_time_unix = strtotime($expire_time)) return $this->error('请选择正确的过期时间');
        if(in_array($type,[1,2]) && ($invest_amount<0 || $stored_value_amount<0 || $give_amount<0)) return $this->error('请选择正确金额');
        if($member_id<1) return $this->error('请绑定会员');

        if($partner_id != 0){

            if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

            if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

            if($partner->is_delete == 1) return $this->error($this->name.'不存在');

            if($partner->role_id != $role_id) return $this->error($this->name.'不存在');

            //判断是否已经存在
            if($partner->mobile != $mobile){

                if(null !== PartnerModel::where([

                        ['shop_id','=',$this->request->shopId],

                        ['is_delete','=',0],

                        ['mobile','=',$mobile],

                    ])->find()){

                    return $this->error('这个手机号已经存在合伙人了');

                }

            }
            if($partner->member_id != $member_id){

                if(null !== PartnerModel::where([

                        ['shop_id','=',$this->request->shopId],

                        ['is_delete','=',0],

                        ['member_id','=',$member_id],

                    ])->find()){

                    return $this->error('会员已绑定其他合伙人');

                }

            }



        }else{

            $partner = new PartnerModel();
            $partner->shop_id = $this->request->shopId;
            $partner->role_id = $role_id;
            if(null !== PartnerModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0],

                    ['mobile','=',$mobile],

                ])->find()){

                return $this->error('这个手机号已经存在合伙人了');

            }
            if(null !== PartnerModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0],

                    ['member_id','=',$member_id],

                ])->find()){

                return $this->error('会员已绑定其他合伙人');

            }

        }
        Db::startTrans();

        try{
            if($partner_id != 0){
                $partner->name = $name;
                $partner->mobile = $mobile;
                $partner->save();
            }else{
                //分红股票获取
                $bonus_set = PartnerBonusSettingModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
                $bonus_share_get_type = explode(',',$bonus_set->bonus_share_get_type);
                $bonus_share=0;
                if(in_array($type,$bonus_share_get_type)){
                    if($type==1){
                        $bonus_share = $invest_amount/$bonus_set->per_share_price;
                    }
                    if($type==2){
                        $bonus_share = $stored_value_amount/$bonus_set->per_share_price;
                    }
                    $partner->bonus_share = round($bonus_share);
                    //分红股票是否已不够
                    if($bonus_set->residue_share_num<$partner->bonus_share) return $this->error('分红股票已不够');
                }
                $partner->member_id = $member_id;
                $partner->name = $name;
                $partner->mobile = $mobile;
                //$partner->expire_time = $expire_time;
                if($type==1){
                    $partner->invest_amount = $invest_amount;
                }
                //储值金不能修改（储值金为储值卡的钱，与单店版会员详情的余额充值钱一个道理）
                if($type==2 && $partner_id<1){
                    $partner->stored_value_amount = $stored_value_amount;
                    $partner->give_amount = $give_amount;
                }
                $partner->type = $type;

                //有效期
                $dividend_set = PartnerDividendSettingModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'role_id'=>$role_id])->find();
                if($dividend_set->valid_type>0){
                    $partner->valid_start_time = date("Y-m-d")." 00:00:00";
                    $partner->valid_end_time = date("Y-m-d",strtotime("+".$dividend_set->valid_type." year"))." 23:59:59";
                }

                $partner->valid_type = $dividend_set->valid_type;

                $partner->save();

                //分红股总剩余发行量自减
                $pbs_model = new PartnerBonusSettingModel();
                $re = $pbs_model->dec(['shop_id'=>$this->request->shopId,'is_delete'=>0],'residue_share_num',$bonus_share);

                //储值金额增加到会员的余额（单店版的余额就是门店储值卡的概念）
                if($type==2){
                    $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
                    $MemberWalletLogic->addBalance($stored_value_amount, $give_amount, 22,'储值合伙人', $this->request->accountId);

                    //获取分红股记录表
                    $bonus = $pbs_model->where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
                    $log = new PartnerBonusShareLogModel();
                    $log->shop_id = $this->request->shopId;
                    $log->member_id = $member_id;
                    $log->partner_id = $partner->partner_id;
                    $log->role_id = $partner->role_id;
                    $log->bonus_share = $bonus_share;
                    $log->store_value_amount = $stored_value_amount;
                    $log->give_amount = $give_amount;
                    $log->residue_share_num = $bonus->residue_share_num;
                    $log->save();
                }
            }


            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('保存成功');



    }
    /*分红信息,只有投资和储值并且被选中分红股票获取渠道才有*/
    public function bonus(){
        $type = $this->request->param('type/d',0);
        $price = $this->request->param('price/f',0);
        $return = [];

        $bonus_setting = PartnerBonusSettingModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        //$bouus_num=PartnerModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1])->sum('bonus_share');
        if($bonus_setting){
            $bonus_share_get_type = explode(',',$bonus_setting['bonus_share_get_type']);
            if(in_array($type,$bonus_share_get_type)){
                $bonus_share=0;
                if($type==1){
                    $bonus_share = $price/$bonus_setting->per_share_price;
                }
                if($type==2){
                    $bonus_share = $price/$bonus_setting->per_share_price;
                }
                $return = [
                    'bonus_share'=> round($bonus_share),
                    'per_share_price'=>$bonus_setting->per_share_price,
                    'residue_share_num'=>$bonus_setting->residue_share_num,
                    //'residue_share_num'=>$bonus_setting->total_share_num-$bouus_num,
                ];
            }
        }
        return $this->success($return);
    }
    /*退股*/
    public function withdrawal()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if(!in_array($partner->role_id,[2,5,6])) return $this->error($this->name.'不存在');

        if($partner->status == -1 ) return $this->error($this->name.'已经退股了，请勿重复操作');

        //其他判断，待补充



        $partner->status=-1;

        $partner->save();
        //退股之后退还股份
        $pbs_model = new PartnerBonusSettingModel();
        $re = $pbs_model->inc(['shop_id'=>$this->request->shopId,'is_delete'=>0],'residue_share_num',$partner->bonus_share);

        return $this->success('操作成功');

    }
    /*删除*/
    public function del()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if(in_array($partner->role_id,[2,5,6])){

            if($partner->status != -1) return $this->error('还未退股，无法删除');

        }

        //其他判断，待补充



        $partner->is_delete=1;

        $partner->save();

        return $this->success('操作成功');

    }
    /*延期*/
    public function delay()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $expire_time=$this->request->param('expire_time');



        if(empty($expire_time)) return $this->error('请选择过期时间');

        if(false === $expire_time_unix = strtotime($expire_time)) return $this->error('请选择正确的过期时间');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if(!in_array($partner->role_id,[2,5,6])) return $this->error($this->name.'不存在');

        if($partner->status == -1 ) return $this->error($this->name.'已经退股了,无法删除');



        $partner->expire_time = $expire_time;

        $partner->save();

        return $this->success('操作成功');

    }

}

